import re
import time
import paramiko
import datetime
from global_parameter import os_password, get_su_path, sys_log_file_path

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

"""
            操作系统	    应用系统
区域与账号	oetsky	        oetsky
湖南	    oetsky@28569	oetsky@97258
湖北	    oetsky@21291	oetsky@93625
山东		oetsky@85739	oetsky@67983
山西		oetsky@82936	oetsky@97652
福建		oetsky@75623	oetsky@37268
江苏		oetsky@75638	oetsky@47432
浙江		oetsky@87942	oetsky@45296
广东		oetsky@42583	oetsky@23567
新疆		oetsky@39854	oetsky@57428
安徽		oetsky@57192	oetsky@75614
甘肃		oetsky@27682	oetsky@25263
四川		oetsky@18482	oetsky@97782
"""


def ssh_exe_cmd(cmd):
    global ssh
    stdin, stdout, stderr = ssh.exec_command(cmd)
    output_str = stdout.read().decode('utf-8')
    return output_str


def channel_exe_cmd(channel, cmd, end_flag="# "):
    channel.send(cmd)
    channel.send("\n")
    buff = ''
    status = True
    while not buff.endswith(end_flag):
        resp = channel.recv(9999)
        # 出现异常字符时忽略
        buff += resp.decode('utf-8', errors='ignore')
        if "su: 鉴定故障" in buff:
            status = False
            break
    return buff, status


def get_web_password(ip, port, username, password):
    """
    获取站端网页访问的每日密码
    :param ip:
    :param port:
    :param username:
    :param password:
    :return:
    """
    # 修改centos系统时间为当前时间
    modify_centos_date(ip, port=10088, username="oetsky", password=os_password,
                       centos_date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # 等待3秒，让系统时间、硬件时间都生效
    time.sleep(3)

    now = datetime.datetime.now()
    str_now = now.strftime("%Y-%m-%d")
    print(str_now)
    ssh.connect(hostname=ip, port=port, username=username, password=password)
    channel = ssh.invoke_shell()
    time.sleep(0.1)
    try:
        ssh_exe_cmd('sudo {}'.format(get_su_path))
        output_str = ssh_exe_cmd('sudo {} --debug'.format(get_su_path))
        # print(output_str)
        su_password = output_str[-7:]
        # print(su_password)

        channel_exe_cmd(channel, "su", end_flag='密码：')
        channel_exe_cmd(channel, su_password)
        # 执行获取密码命令
        grep_data, _ = channel_exe_cmd(channel,
                                       "cat {}SystemOut.log | grep pwd".format(sys_log_file_path))
        current_time = datetime.datetime.now().strftime("%Y-%m-%d")
        match_data = re.findall(r"{}.*?pwd.+\r".format(current_time), grep_data)
        if len(match_data) > 0:
            password_web = match_data[0][-7:-1]
            return password_web
        else:
            # 如果之前方法无法获取到，则使用zcat命令在备份文件中获取
            grep_back_data, _ = channel_exe_cmd(channel,
                                                "zcat {}backup/{}/* |grep  pwd".format(sys_log_file_path, str_now))
            match_back_data = re.findall(r"pwd.+\r", grep_back_data)
            if len(match_back_data) > 0:
                password_web = match_back_data[-1][-7:-1]
                return password_web
            else:
                print("未检测到数据", match_data)
                return None
    except paramiko.ssh_exception.AuthenticationException:
        print('Failed to login. ip username or password not correct.')
        return None
    finally:
        ssh.close()
        channel.close()


def modify_centos_date(ip, port, username, password, centos_date):
    """
    修改站端的系统时间
    :param ip:
    :param port:
    :param username:
    :param password:
    :return:
    """
    try:
        ssh.connect(hostname=ip, port=port, username=username, password=password)
        ssh_exe_cmd('date -s "{}"'.format(centos_date))
        ssh_exe_cmd('clock -w')
        ssh_exe_cmd('hwclock -w')
    except paramiko.ssh_exception.AuthenticationException:
        print('Failed to login. ip username or password not correct.')
        return None


if __name__ == '__main__':
    password_web_1 = get_web_password("192.168.31.12", port=10088, username="oetsky", password=os_password)
    print("192.168.31.12 ：web端访问密码", password_web_1)
